import * as utils from '../../utils/util.js';

const app = getApp();
let that;
Page({

  /**
   * 页面的初始数据
   */
  data: {
     inTheaters:{},
     comingSoon:{},
     top250:{},
     containerShow:true,
     searchPanelShow:false,
     searchResult:{}

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    that = this;
    const inTheaterUrl = app.globalData.g_doubanBase + "/v2/movie/in_theaters" + "?start=0&count=3";
    const comingSoonUrl = app.globalData.g_doubanBase + "/v2/movie/coming_soon" + "?start=0&count=3";
    const top250Url = app.globalData.g_doubanBase + "/v2/movie/top250" + "?start=0&count=3";

    that.getMovieListData(inTheaterUrl,"inTheaters","正在热映");
    this.getMovieListData(comingSoonUrl,"comingSoon","即将上映");
    this.getMovieListData(top250Url,"top250","top250");
  },


  getMovieListData: (url,key,catetoryTitle) => {
    wx.showToast({
      title: '加载中...',
      icon: 'loading',
      mask: true,
   });
    wx.request({
      url: url,
      method: 'GET',
      header: {
        "Content-Type": "application/xml"
      },
      success: (res) => {
        console.log(res.data);
         that.processDoubanData(res.data, key, catetoryTitle);

      },
      fail: (error) => {
        console.log(error);
      },
    })

  },

  processDoubanData: (moviesDouban, key, catetoryTitle)=>{
    const movies=[];
    for (let idx in moviesDouban.subjects){
      const subject = moviesDouban.subjects[idx];
      let title = subject.title;
      if(title.length>=6){
        title = title.substring(0,6)+'...';
      }
      const temp = {
         stars: utils.convertToStarsArray(subject.rating.stars),
        title:title,
        average: subject.rating.average,
        coverageUrl: subject.images.large,
        movieId: subject.id
      }

      movies.push(temp);
    }
    let readyData ={};
    readyData[key]={
      catetorytitle: catetoryTitle,
      movies: movies
    };
    that.setData(readyData);
    
    wx.hideToast();
  },


  onMoreTap:(event)=>{
     const category = event.currentTarget.dataset.category;
      wx.navigateTo({
         url: 'more-movies/more-movies?category=' + category,
      })
  },

  onBindFocus:(event)=>{
    that.setData({
      containerShow:false,
      searchPanelShow:true,
    })
  },

  onBindChange:(event)=>{
    const text = event.detail.value;
    const searchUrl=app.globalData.g_doubanBase+"/v2/movie/search?q="+text;
    console.log(text);
    that.getMovieListData(searchUrl,"searchResult",'');

    
  },

  onCancelImgtap:(event)=>{
    that.setData({
      containerShow:true,
      searchPanelShow:false,
      searchResult:{}
    })
  },


  onMovieTap:(event)=>{
    const movieId = event.currentTarget.dataset.id;
    console.log(movieId);
    wx.navigateTo({
      url: 'movie-detail/movie-detail?id='+movieId,
    })
  },

})